from constant import YX_URL, YX_appid, YX_appToken, YX_displayNumber, YX_templateId
import requests
import json
import time
import hashlib
import base64
from inits import logger

class http_phone:
    def __init__(self):
        self.url = YX_URL
        self.app_id = YX_appid
        self.app_token = YX_appToken
        self.display_number = YX_displayNumber
        self.template_id = YX_templateId

    def send_phone_code(self, phone, shop_name, call_phone):
        # 时间戳
        timestamp = int(time.time() * 1000)

        if not phone:
            phone = "未填写"

        param = {
            "calleeNumber": call_phone,
            "templateId": self.template_id,
            "displayNumber": self.display_number,
            "templateArgs": {
                "var1": phone,
                "var2": shop_name
            }
        }

        header = {
            "Authorization": self.base_six(timestamp=timestamp),
            'Content-Type': 'application/json'
        }
        print(header)
        print(param)
        # 将字典转换为JSON格式
        json_data = json.dumps(param)
        json_header = json.dumps(header)

        url = self.url.format(self.app_id, self.sig(timestamp=timestamp))
        print(url)

        # 关闭python的SSL
        res = requests.post(url=url, json=param, headers=header, verify=False)
        res_data = res.json()
        print(res_data)
        logger.error("云信电话接口数据 ：" + json.dumps(res_data))

    def sig(self, timestamp):
        param = "{}{}{}".format(self.app_id, self.app_token, str(timestamp))
        m = hashlib.new('md5', param.encode('utf-8'))
        return m.hexdigest()

    def base_six(self, timestamp):
        param = "{}:{}".format(self.app_id, str(timestamp))
        data = str(base64.b64encode(param.encode('utf-8')), 'utf-8')
        return data